//
//  ViewController.m
//  吉它-调音器
//
//  Created by 123 on 2022/9/14.
//

#import "ViewController.h"
#import "WT_HZ.h"
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
#import "UtilsMacros.h"
#import "FontAndColorMacros.h"
#import "ThirdMacros.h"
#import "MyBtton.h"
#import "Tools.h"

#define WTHZ [WT_HZ shareWT_HZ]
@interface ViewController ()<AVAudioPlayerDelegate>
{
    UIImageView * selectBottonImg;
    MyBtton * selectBtn;
    
    NSArray *_HZArray;
    NSArray *_ValueArr;
    
    float minValue;
    float nowValue;
    float maxValue;
    UIImageView * header_other;
    UIImageView * header_now;
    
    AVAudioPlayer *_audioPlayer;
    BOOL isPlay;
    
    int jsNum;
}
@end

@implementation ViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [WTHZ stopWTAudio];
    [WTHZ destroyWTAudio];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [WTHZ stopWTAudio];
    [WTHZ destroyWTAudio];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = COLOR(250,250,250);
    UILabel * navtitle = UILABEL_ALLOC(0, kStatusBarHeight, KScreen_W, 44);
    navtitle.font = FontBold(18);
    navtitle.textColor = ColorHex(@"ffffff");
    navtitle.textAlignment = NSTextAlignmentCenter;
    navtitle.text = @"吉他-调音器";
    [self.view addSubview:navtitle];
    
    UIImageView * header = UIIMAGEVIEW_ALLOC(Ratio(11.5), KNav_H+(KScreen_H-Ratio(379)-KSafeAreaBottomHeight-KNav_H)/2-Ratio(75), Ratio(352), Ratio(150));
    header.image = KImageNamed(@"Tuner_headerBg");
    [self.view addSubview:header];
    
    header_other = UIIMAGEVIEW_ALLOC(Ratio(9), header.frame.origin.y+Ratio(28), Ratio(44), Ratio(28));
    header_other.image = KImageNamed(@"Tuner_太低");
    header_other.hidden = YES;
    [self.view addSubview:header_other];
    
    header_now = UIIMAGEVIEW_ALLOC(Ratio(171), header.frame.origin.y+Ratio(25), Ratio(30), Ratio(34));
    header_now.image = KImageNamed(@"Tuner_正确");
    header_now.hidden = YES;
    [self.view addSubview:header_now];
    
    UIImageView * botton = UIIMAGEVIEW_ALLOC(Ratio(76), KScreen_H-Ratio(379)-KSafeAreaBottomHeight, Ratio(222), Ratio(379));
    botton.image = KImageNamed(@"Tuner_botton");
    [self.view addSubview:botton];
    
    selectBottonImg = UIIMAGEVIEW_ALLOC(Ratio(76), KScreen_H-Ratio(379)-KSafeAreaBottomHeight, Ratio(222), Ratio(379));
    [self.view addSubview:selectBottonImg];
    
    NSArray * arr = [[NSArray alloc]initWithObjects:@"D",@"G",@"A",@"B",@"E",@"E", nil];
    for (int i=0; i<arr.count; i++) {
        MyBtton * btn = [[MyBtton alloc]initWithFrame:CGRectMake(Ratio(24)+(i%2)*Ratio(290), KScreen_H-Ratio(379)-KSafeAreaBottomHeight+Ratio(52)+i/2*Ratio(70), Ratio(36), Ratio(36))];
        [btn setBackgroundImage:KImageNamed(@"Tuner_背影色") forState:UIControlStateNormal];
        [btn setBackgroundImage:KImageNamed(@"Tuner_选中背影色") forState:UIControlStateSelected];
        [btn setTitle:arr[i] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        btn.titleLabel.textAlignment = NSTextAlignmentCenter;
        btn.titleLabel.font = FontBold(18);
        [btn addTarget:self action:@selector(clickTap:) forControlEvents:UIControlEventTouchUpInside];
        btn.tag = i;
        [self.view addSubview:btn];
    }
    
    _ValueArr = [[NSArray alloc]initWithObjects:@"146.832",@"195.998",@"110.000",@"246.942",@"82.407",@"329.628", nil];
    _HZArray = [[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"HZArray" ofType:@"plist"]];
//    NSError *error = nil;
//       NSData *jsonData = [NSJSONSerialization dataWithJSONObject:_HZArray options:NSJSONWritingPrettyPrinted error:&error];
//       NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//       NSString *jsonTemp = [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
//
//    NSLog(@"===%@",jsonTemp);
//    _standerd_note = [[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"standerd_note" ofType:@"plist"]];
}
- (void)clickTap:(MyBtton *)sender{
    if (sender.tag == 5) {
        selectBottonImg.image = KImageNamed(@"TunnerLine_E1");
        [self PlayAudio:@"E5"];
    }else{
        NSString * imgname = [NSString stringWithFormat:@"TunnerLine_%@",sender.titleLabel.text];
        selectBottonImg.image = KImageNamed(imgname);
        if (sender.tag == 2 || sender.tag == 4) {
            [self PlayAudio:[NSString stringWithFormat:@"%@3",sender.titleLabel.text]];
        }else{
            [self PlayAudio:[NSString stringWithFormat:@"%@4",sender.titleLabel.text]];
        }
    }
    if (sender.selected) {
        return;
    }
    float a = [_ValueArr[sender.tag] floatValue];
    for (int i=0; i<_HZArray.count; i++) {
        if (a == [_HZArray[i] floatValue]) {
            NSLog(@"index === %d====%0.3f",i,a);
            minValue = [_HZArray[i-1] floatValue];
            nowValue = a;
            maxValue = [_HZArray[i+1] floatValue];
            break;
        }
    }
    if (selectBtn != nil) {
        selectBtn.selected = NO;
    }else{
        /**
         *
         *  检测声音频率的核心
         *
         *  将检测到的声音频率，通过HZArray.plist和standerd_note.plist对应的声音频率表，翻译成对应的音调
         */
        // initialize stuff
        [WTHZ creatWTAudio];
        [WTHZ startWTAudioCallBack:^(float MAX_HZ) {
            [self changeUIWithHZParmaters:MAX_HZ];
        }];
    }
    sender.selected = YES;
    selectBtn = sender;
    
    
}
- (void)changeUIWithHZParmaters:(float)MAX_HZ {
    if (isPlay) {
        return;
    }
    if (MAX_HZ<50 || MAX_HZ>600) {
        return;
    }
    if (nowValue-(nowValue-minValue)*0.17 < MAX_HZ && nowValue+(maxValue-nowValue)*0.17 > MAX_HZ) {
        jsNum = jsNum+1;
        header_now.hidden = NO;
        header_other.hidden = YES;
        if (jsNum == 1) {
            [self PlayAudio:@"bingo"];
        }
    }else{
//        jsNum = 0;
        if (nowValue > MAX_HZ) {
            float pj = (nowValue-minValue)/2;
            if (MAX_HZ < minValue+pj) {
                header_other.image = KImageNamed(@"Tuner_太低");
            }else{
                header_other.image = KImageNamed(@"Tuner_偏低");
            }
            float x = (nowValue-minValue)/Ratio(175);
            float a = (MAX_HZ-minValue);
            if (a < 0) {
                a = 0;
            }
            x = a*x;
            header_other.frame = CGRectMake(x+Ratio(11.5)-Ratio(22), header_other.frame.origin.y, header_other.frame.size.width, header_other.frame.size.height);
        }else{
            float pj = (maxValue-nowValue)/2;
            if (MAX_HZ < nowValue+pj) {
                header_other.image = KImageNamed(@"Tuner_偏高");
            }else{
                header_other.image = KImageNamed(@"Tuner_太高");
            }
            float x = (maxValue-nowValue)/Ratio(175);
            float a = (maxValue-MAX_HZ);
            if (a < 0) {
                a = 0;
            }
            x = a*x;
            header_other.frame = CGRectMake((Ratio(11.5)+Ratio(352))-Ratio(22)-x, header_other.frame.origin.y, header_other.frame.size.width, header_other.frame.size.height);
        }
        header_other.hidden = NO;
        header_now.hidden = YES;
    }
}
-(void)PlayAudio:(NSString *)name{
//    isPlay = YES;
    NSString* soundFilePath;
    soundFilePath =[[NSBundle mainBundle]pathForResource:name ofType:@"mp3"];
    NSURL*soundURL = [NSURL fileURLWithPath:soundFilePath];
    // 初始化播放器，注意这里的Url参数只能为本地文件路径，不支持HTTP Url
    NSError *error = nil;
    _audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:soundURL error:&error];
    _audioPlayer.delegate = self;
    //设置播放器属性
    _audioPlayer.numberOfLoops = 0;// 不循环
//        _audioPlayer.delegate = self;
    _audioPlayer.volume = 1; // 音量
    [_audioPlayer prepareToPlay];// 加载音频文件到缓存【这个函数在调用play函数时会自动调用】
   
    if(error){
      NSLog(@"初始化播放器过程发生错误,错误信息:%@",error.localizedDescription);
  
    }
    [_audioPlayer play];
    
   
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    isPlay = NO;
}
@end
